<?php
namespace app\system\model;
use app\base\model\BaseModel;
/**
 * 用户组操作
 */
class SystemGroupModel extends BaseModel {
    //完成
    protected $_auto = array (
         array('status','intval',3,'function'),
         array('name','htmlspecialchars',3,'function'),
     );
    //验证
    protected $_validate = array(
        array('name','1,20', '用户组名称只能为1~20个字符', 0 ,'length',3),
        array('parent_id','parentCheck', '上级角色选择错误！', 1 ,'callback',2),
    );

    protected function _saveBefore($data){
        $data['menu_purview'] = serialize($data['menu_purview']);
        $data['base_purview'] = serialize($data['base_purview']);
        return $data;
    }

    /**
     * 获取列表
     * @return array 列表
     */
    public function loadList($where = array(), $limit = 0, $order = '',$classId = 0){
        $data = $this->where((array)$where)->limit($limit)->order("group_id ASC")->select();
        $cat = new \variant\ext\Category(array('group_id', 'parent_id', 'name', 'cname'));
        $data = $cat->getTree($data, intval($classId));
        return $data;
    }

    /**
     * 检查上级角色
     * @return string
     */
    public function parentCheck()
    {
        //获取变量
        $groupId = request('post.group_id');
        $parentId = request('post.parent_id');

        //判断空上级
        if(!$parentId){
            return true;
        }
        // 分类检测
        if ($groupId == $parentId){
            $this->error = '当前角色不能为上级角色！';
            return false;
        }

        $cat = $this->loadList('',0,'',$classId);
        if(empty($cat)){
            return true;
        }
        foreach ($cat as $vo) {
            if ($parentId == $vo['class_id']) {
                $this->error = '上级角色不能为子角色！';
                return false;
            }
        }
        return true;
    }

    /**
     * 获取递归权限
     * @param int $groupId 用户组
     * @return array
     */
    public function loadCrumb($groupId)
    {
        $data = $this->select();
        $cat = new \variant\ext\Category(array('group_id', 'parent_id', 'name', 'cname'));
        $data = $cat->getPath($data, $groupId);
        $basePurview = array();
        $menuPurview = array();
        if(!empty($data)){
            foreach ($data as $key => $value) {
                $basePurview = array_merge((array)$basePurview,(array)unserialize($value['base_purview']));
                $menuPurview = array_merge((array)$menuPurview,(array)unserialize($value['menu_purview']));
            }
        }
        $info = array();
        $info['base_purview'] = $basePurview;
        $info['menu_purview'] = $menuPurview;
        return $info;
    }

    /**
     * 获取所有动作权限
     */
    public function getPurview(){
        $list = get_all_service('Purview','System');
        if(empty($list)){
            return $list;
        }
        return $list;
    }

}
